package com.vrv.netmgr.entry;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import com.vrv.common.GlobalConstants;
import com.vrv.common.SettingDialog;
import com.vrv.common.SettingDialog.MyDialogInt;
import com.vrv.common.WaitingDialog;
import com.vrv.common.config.EdpSharedPreferences;
import com.vrv.common.util.SharedPreferencesHelper;
import com.vrv.common.util.StringUtils;
import com.vrv.netmgr.R;
import com.vrv.netmgr.persistent.LoginSharedPreferencesHelper;
import com.vrv.netmgr.usermgr.UserManager;
import com.vrv.netmgr.vo.LoginInfo;

/**
 * @Description 登录
 *
 * @author gaopei
 * @date
 */
public class LoginActivity extends Activity {

    private static final String TAG = LoginActivity.class.getSimpleName();

    private static final boolean DEBUG = true && GlobalConstants.DEBUG;
    /**
     * 返回键
     */
    private boolean isBack = false;
    /**
     * 登录
     */
    private static final int LOGIN = 0;
    /**
     * 账号
     */
    private EditText accountExt;
    /**
     * 密码
     */
    private EditText passwdExt;
    /**
     * 记住密码
     */
    private CheckBox rememberPasswdChk;
    /**
     * 登录
     */
    private ImageButton loginBtn;
    /**
     * 等待对话框
     */
    private WaitingDialog waitingDialog;
    /**
     * 处理器
     */
    private Handler handler;
    /**
     * 登录信息
     */
    private int isSuccess;
    /**
     * 判断是否记住密码
     */
    private  LoginInfo loginInfo ;
    /**
     * 判断是否自动登录
     */
    private CheckBox autoLogin;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_login);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.common_title);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        init();
    }

    /**
     * 获取服务器地址
     */
    public boolean getServerMsg() {
        if (DEBUG)
            Log.v(TAG, "getServerMsg()");

        SharedPreferencesHelper sHelper = new SharedPreferencesHelper(this, EdpSharedPreferences.ServerSetting.SERVER_INFO_FILENAME);
        String data = sHelper.getValue(EdpSharedPreferences.ServerSetting.SERVER_IP_KEY);

        if (StringUtils.isBlank(data)) {
            return false;
        }
        Log.i("server ip", data);

        return true;
    }

    /**
     * 保存服务器地址 ip地址 port端口号
     */
    public void saveServerMsg(String ip, String port, SettingDialog mad) {
        if (DEBUG)
            Log.v(TAG, "saveServerMsg()");
        //
        String regEx = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";
        Pattern pattern = Pattern.compile(regEx);
        Matcher matcher = pattern.matcher(ip);
        if (!matcher.matches()) {
            Toast.makeText(LoginActivity.this, "服务器地址输入不合法", Toast.LENGTH_LONG).show();
            return;
        } else {
            SharedPreferencesHelper sHelper = new SharedPreferencesHelper(this, EdpSharedPreferences.ServerSetting.SERVER_INFO_FILENAME);
            sHelper.putValue(EdpSharedPreferences.ServerSetting.SERVER_IP_KEY, ip);
        }

        //
        regEx = "^[0-9_]+$";
        pattern = Pattern.compile(regEx);
        matcher = pattern.matcher(port);
        if (!matcher.matches()) {
            Toast.makeText(LoginActivity.this, "端口号输入不合法", Toast.LENGTH_LONG).show();
            return;
        } else {
            SharedPreferencesHelper sHelper = new SharedPreferencesHelper(this, EdpSharedPreferences.ServerSetting.SERVER_INFO_FILENAME);
            sHelper.putValue(EdpSharedPreferences.ServerSetting.SERVER_PORT_KEY, port);
            mad.dismiss();
        }
    }

    /**
     * 设置服务器地址
     */
    public void initServer() {
        if (DEBUG)
            Log.v(TAG, "initServer()");

        /** 获取本地配置信息 */
        SharedPreferencesHelper sHelper = new SharedPreferencesHelper(this, EdpSharedPreferences.ServerSetting.SERVER_INFO_FILENAME);
        String ipValue = sHelper.getValue(EdpSharedPreferences.ServerSetting.SERVER_IP_KEY);
        String portValue = sHelper.getValue(EdpSharedPreferences.ServerSetting.SERVER_PORT_KEY);
        /** 保存服务器地址端口号 update by zxb 20130624 */
        //初始化自定义的Dialog
        final SettingDialog mad = new SettingDialog(LoginActivity.this);
        //
        mad.setIp(ipValue);
        mad.setPort(portValue);
        mad.setLeftButton("确定", new MyDialogInt() {
			public void onClick(View view) {
				String ip = mad.getIp();
                String port = mad.getPort();
                saveServerMsg(ip, port, mad);
			}
		});
        mad.setRightButton("取消", new MyDialogInt() {
			public void onClick(View view) {
				mad.dismiss();
			}
		});
    }

    @SuppressLint("HandlerLeak")
    private void init() {
        if (DEBUG)
            Log.v(TAG, "init()");

        TextView title = (TextView) findViewById(R.id.title_text);
        title.setText("用户登录");

        accountExt = (EditText) findViewById(R.id.accountExt);
        passwdExt = (EditText) findViewById(R.id.passwdExt);
        rememberPasswdChk = (CheckBox) findViewById(R.id.rememberPasswdChk);
        //
        autoLogin = (CheckBox) findViewById(R.id.autoLogin);
        //
        loginBtn = (ImageButton) findViewById(R.id.loginBtn);
        loginBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (prepare()) {
                	//创建等待对话框
                    waitingDialog = WaitingDialog.createDialog(LoginActivity.this);
                    waitingDialog.setTitile("登录中...").setMessage("登录中...").show();
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            login();
                            handler.sendEmptyMessage(LOGIN);
                        }
                    }).start();
                }
            }
        });

        handler = new Handler() {
            public void handleMessage(Message msg) {
                waitingDialog.dismiss();
                switch (msg.what) {
                case LOGIN:
                    if (isSuccess == UserManager.LOGIN_SUCCESS) {
                    	if(rememberPasswdChk.isChecked() || autoLogin.isChecked()){
                    		LoginSharedPreferencesHelper.saveLoginInfo(getApplicationContext(), populateLoginInfo());
                    	}else{
                    		LoginInfo loginInfo = new LoginInfo();
                    		loginInfo.setRememberPasswd(false);
                    		loginInfo.setAutoLogin(false);
                    	}

                        Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
                        forward();

                    } else if (isSuccess == UserManager.LOGIN_INPUTERR) {
                        Toast.makeText(LoginActivity.this, "密码或账号错误", Toast.LENGTH_LONG).show();
                    } else if (isSuccess == UserManager.LOGIN_NETERR) {
                        Toast.makeText(LoginActivity.this, "网络连接失败", Toast.LENGTH_LONG).show();
                    }
                    break;
                }

            }
        };
        // 初始化记住密码和登录信息
        loginInfo = LoginSharedPreferencesHelper.getLoginInfo(getApplicationContext());
        if(loginInfo.isRememberPasswd() || loginInfo.isAutoLogin()){
        	initLoginInfo();
        	if(loginInfo.isAutoLogin()){
               forward();
        	}
        }
    }

    /**
     * 进入主界面
     */
    private void forward() {
        Intent intent = new Intent();
        intent.setClass(LoginActivity.this, MainTab.class);
        LoginActivity.this.startActivity(intent);
        finish();
    }

    /**
     * 初始化登录信息
     */
    private void initLoginInfo() {

        if (loginInfo != null) {
        	if(loginInfo.isRememberPasswd()){
        		rememberPasswdChk.setChecked(true);
        	}
        	if(loginInfo.isAutoLogin()){
        		rememberPasswdChk.setChecked(true);
        		autoLogin.setChecked(true);
        	}

            String name = loginInfo.getLoginName();
            if (StringUtils.isNotBlank(name)) {
                accountExt.setText(name);
                accountExt.setSelection(name.length());
            }
            passwdExt.setText(loginInfo.getLoginPasswd());
        }
    }

    /**
     * 准备登录
     *
     * @return
     */
    private boolean prepare() {
        if (false == getServerMsg()) {
            initServer();
            return false;
        }
        String str_account = accountExt.getText().toString().trim();
        if (StringUtils.isBlank(str_account)) {
            Toast.makeText(LoginActivity.this, "账号不能为空.", Toast.LENGTH_SHORT).show();
            return false;
        }
        String passwd = passwdExt.getText().toString().trim();
        if (StringUtils.isBlank(passwd)) {
            Toast.makeText(LoginActivity.this, "密码不能为空.", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    private void login() {
        // try {
        // String desAccount = DES.encryptDES(accountExt.getText().toString(),
        // GlobalConstants.DES_KEY);
        // String desPasswd = DES.encryptDES(passwdExt.getText().toString(),
        // GlobalConstants.DES_KEY);
        // String account = DES
        // .decryptDES(desAccount, GlobalConstants.DES_KEY);
        // String passwd = DES.decryptDES(desPasswd, GlobalConstants.DES_KEY);
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        Map<String, String> map = new HashMap<String, String>();
        map.put(GlobalConstants.USER_NAME, accountExt.getText().toString());
        map.put(GlobalConstants.PASSWORD, passwdExt.getText().toString());
        isSuccess = new UserManager().isRightUser(getApplicationContext(), map);
    }

    /**
     * 收集用户登录信息
     *
     * @return
     */
    private LoginInfo populateLoginInfo() {
        LoginInfo loginInfo = new LoginInfo();
        loginInfo.setLoginName(accountExt.getText().toString().trim());
        loginInfo.setLoginPasswd(passwdExt.getText().toString());
        if(rememberPasswdChk.isChecked()){
        	loginInfo.setRememberPasswd(rememberPasswdChk.isChecked());
        }
        if(autoLogin.isChecked()){
        	loginInfo.setRememberPasswd(rememberPasswdChk.isChecked());
        	loginInfo.setAutoLogin(autoLogin.isChecked());
        }
        return loginInfo;
    }

    @Override
    protected void onPause() {
        if (waitingDialog != null) {
        	waitingDialog.dismiss();
        }
        super.onPause();
    }

    // 监听返回键
    Handler backHandler = new Handler() {
        public void handleMessage(Message msg) {
            isBack = false;
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isBack) {
                isBack = true;
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                backHandler.sendEmptyMessageDelayed(0, 2000);
            } else {
                finish();
                System.exit(0);
            }
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.server_addr_set, menu);

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case R.id.action_set:
            initServer();
        }
        return super.onOptionsItemSelected(item);
    }
}
